<template>
  <div class="login-setting">
    <el-form
      ref="userForm"
      :model="userInfo"
      :rules="rules"
      label-width="120px"
      style="margin-left: 120px; margin-top: 30px"
    >
      <el-form-item label="姓名:" prop="username">
        <el-input v-model="userInfo.username" style="width: 300px" />
      </el-form-item>

      <el-form-item label="密码:" prop="password">
        <el-input
          v-model="userInfo.password"
          type="password"
          style="width: 300px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="hSubmit">更新</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
import { getUserDetailById, saveUserDetailById } from '@/api/user'

export default {
  data() {
    return {
      userInfo: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '用户名不能为空', triggler: 'blur' }],
        password: [{ required: true, message: '密码不能为空', triggler: 'blur' }]
      }
    }
  },

  created() {
    this.loadUserDetailById()
  },

  methods: {
    async loadUserDetailById() { // 获取到用户信息
      const res = await getUserDetailById(this.$route.query.id)
      console.log('获取到用户信息', res)
      //   const { username, password, id } = res.data// 获取到要修改的数据项
      //   this.userInfo = { username, password, id }
      this.userInfo = res.data
      // 此处因后端问题, 完成修改项后其他项会进行重置,返回空值导致错误, 直接获取全部信息再行返回便可解决
    },

    async doSave() { // 执行保存
      const res = await saveUserDetailById(this.userInfo)
      console.log('执行保存', res)
    },

    hSubmit() { // 兜底检验
      this.$refs.userForm.validate(valid => {
        if (valid) {
          this.doSave()
        }
      })
    }

  }

}
</script>
